package com.zhanghe.study.poi;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zh
 * @date 2022/3/12 17:19
 */
public class ReadXls {

    public static List<Question> readFromXls(int sheet) throws IOException {
        File file = new File("/Users/zhanghe/Desktop/考试.xlsx");

        XSSFWorkbook hssfWorkbook = new XSSFWorkbook(new FileInputStream(file));

        XSSFSheet hssfSheet = hssfWorkbook.getSheetAt(sheet);
        System.out.println(hssfSheet.getSheetName());

        int rowEnd = hssfSheet.getPhysicalNumberOfRows();

        List<Question> result = new ArrayList<>();

        for (int i = 1; i <= rowEnd - 1; i++) {
            XSSFRow row = hssfSheet.getRow(i);

            Question question = new Question();

            result.add(question);

            for (int k = 0; k < 8; k++) {
                XSSFCell cell = row.getCell(k);

                cell.setCellType(CellType.STRING);
                String stringCellValue = cell.getStringCellValue();

                switch (k) {
                    case 0:
                        // 题型
                        question.setType(stringCellValue);
                        break;
                    case 1:
                        // 题干
                        question.setStem(stringCellValue);
                        break;
                    case 2:
                        // A
                        question.setOptionA(stringCellValue);
                        break;
                    case 3:
                        // B
                        question.setOptionB(stringCellValue);
                        break;
                    case 4:
                        // C
                        question.setOptionC(stringCellValue);
                        break;
                    case 5:
                        // D
                        question.setOptionD(stringCellValue);
                        break;
                    case 6:
                        // E
                        question.setOptionE(stringCellValue);
                        break;
                    case 7:
                        // 答案
                        question.setAnswer(stringCellValue);
                        break;
                }

            }
        }
        return result;

    }
}
